import os
import time
import traceback

import requests
from PyQt5.QtCore import QThreadPool, QRunnable
from bs4 import BeautifulSoup


def getName(mh_name, index):
    # 此方法适用于 全局代理方式代理访问
    proxy_url = "http://127.0.0.1:7890"  # 为本机代理端口及ip
    os.environ['HTTP_PROXY'] = proxy_url
    os.environ['HTTPS_PROXY'] = proxy_url

    headers = {
        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
        'priority': 'u=0, i',
        'referer': 'https://xn--ihqv6vi6hz9a.jyaaa.top/search/3d',
        'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
        'sec-ch-ua-mobile': '?1',
        'sec-ch-ua-platform': '"Android"',
        'sec-fetch-dest': 'document',
        'sec-fetch-mode': 'navigate',
        'sec-fetch-site': 'same-origin',
        'sec-fetch-user': '?1',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36',
    }
    if index == 1:
        response = requests.get(f'https://xn--ihqv6vi6hz9a.jyaaa.top/search/{mh_name}', headers=headers)
    else:
        response = requests.get(f'https://xn--ihqv6vi6hz9a.jyaaa.top/search/{mh_name}/{index}', headers=headers)

    print(response.status_code)
    soup = BeautifulSoup(response.text, 'html.parser')
    b_items = (
        soup.find_all("div", class_="comic-list-item clearfix")
    )
    if len(b_items) == 0:
        return False
    for item in b_items:
        print(
            item.find("p", class_="comic-update-at").text.replace("第", "").replace("話", "").replace("- 最終話", ""),
            item.find("a", class_="cover").get('href').replace("/comic/", ""),
            item.find("img").get('alt'))
    return True


if __name__ == '__main__':
    # for idx in range(100):
        flag = getName("3d", 0)
        # if not flag:
        #     break
